<!--
 * @Author: zhao 13370229059@163.com
 * @Date: 2024-04-13 22:32:10
 * @LastEditors: zhao 13370229059@163.com
 * @LastEditTime: 2024-10-09 14:13:06
 * @FilePath: \dance\pages\index\index2Compontents\course.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <view class="course">
    <view v-for="item in ajax.list" class="item">
      <z-course-card
        :data="item"
        :key="item.id"
        :autoVideo="item.autoVideo"
        :autoLoop="item.autoLoop"
        @onCollect="onCollectSuccess"
        @onVideoEnd="onVideoEnd"
      ></z-course-card>
    </view>
    <view v-if="ajax.list.length === 0" class="course-empty">
      <uv-empty mode="list" text="未找到匹配的搜索结果"></uv-empty>
    </view>
  </view>
  <uv-toast ref="toastRef"></uv-toast>
</template>

<script setup>
  import dayjs from '@/uni_modules/uv-ui-tools/libs/util/dayjs.js';
  import { onLoad, onReady, onPullDownRefresh, onReachBottom } from '@dcloudio/uni-app';
  import weekday from '@/common/js/weekday.js';
  import { isTimeNull, getWeek, isFileType, toastFn } from '@/common/js/fn.js';
  dayjs.extend(weekday);
  import { ref, reactive, computed, defineProps, watch, defineExpose } from 'vue';
  let toastRef = ref();
  // 这个方法建立在dom元素的高度，都是固定的前提下。如果是瀑布流，这个需要重新写
  let sonComputerEventFn = val => {
    
    // 计算出每一个dom的高度
    let height = val.scrollHeight / Math.ceil(ajax.list.length / 2);
    // acitve 是现在滚到第几行了
    let active = Math.ceil(val.scrollTop / height);
    // 先干掉上一个显示的
    let activeIndex = ajax.list.findIndex(r => r.autoVideo);
    if (activeIndex >= 0) ajax.list[activeIndex].autoVideo = false;
    let newItemNoVideo = 0;
    for (let index = 0; index < ajax.list.length; index++) {
      let val = ajax.list[index];
      val.autoVideo = false;
      if (index >= active * 2) {
        //如果连续4个都没有，那就这次滚动就不要展示播放视频了。
        if (newItemNoVideo >= 4) break;
        if (val.video.dynamicCover) {
          val.autoVideo = true;
          newItemNoVideo = 0;
          // 如果自动滚动，到当前行，发现单数有视频，那就证明前面的一个肯定是没视频的。 那就让他一直循环。
          if (index % 2) {
            val.autoLoop = true;
          } else {
            // 如果是双数，那就看下一个有没有视频。如果下一个没有视频，那就证明这一行只有一个有视频，那当前的就是会一直循环
            val.autoLoop = !ajax.list[index + 1].video.dynamicCover;
          }
          break;
        } else {
          // 如果当前的这一个，没有video。那就跳到下一个。
          newItemNoVideo++;
          continue;
        }
      }
    }
  };
  const onVideoEnd = () => {
    // 看当前播放的是谁
    let index = ajax.list.findIndex(r => r.autoVideo);
    // 如果当前是 自动循环的，那我上面已经判断过，当前行他只有一个视频，能播放。那就不用管
    if (ajax.list[index].autoLoop) {
      return;
    } else {
      // 进了这。意味着，当前行肯定二个视频都能播放。
      ajax.list[index].autoVideo = false;
      // 看当前播放是双数还是单数
      ajax.list[index + (index % 2 ? -1 : 1)].autoVideo = true;
    }
  };
  let ajax = reactive({
    list: []
  });
  let props = defineProps({
    modelValue: {
      type: Number,
      default: 0
    }
  });
  let params = reactive({
    pageSize: 10,
    currentPage: 1,
    keyword: '',
    start: '',
    end: '',
    orderBy: []
  });
  let total = ref(0);
  // 请求推荐数据
  const httpHomeRecommend = async type => {
    let { timetables, pagination } = await uni.$uv.http.post('/app/home/lessons', params);
    total.value = pagination.total;
    let list = timetables.map(r => {
      let video = {},
        teacher = {},
        lesson = r.lesson || {};
      if (r.classify === 'OnlineLesson') {
        video = {
          dynamicCover: r.dynamicCover,
          address: r.dynamicCover,
          cover: r.lessonPhoto
        };
        teacher = {
          username: r.teacherName,
          profilePhoto: r.teacherPhoto
        };
        lesson = { name: r.lessonName };
      } else {
        video = {
          dynamicCover: r.dynamicCover || r.video?.dynamicCover,
          address: r.classify === 'Video' ? r.address : r.video.address,
          cover: r.classify === 'Video' ? r.cover : r.video.cover
        };
        teacher = r.teacher || r.lesson.teacher;
      }
      return {
        week: getWeek(r.issueDate) + ' ' + r.timeDuration,
        ...r,
        video,
        collected: r.classify === 'Video' ? r.collected : r.collected,
        teacher,
        lesson,
        autoVideo: false,
        autoLoop: false
      };
    });
    // 重置的话，就是全面更新，主要用于搜索
    if (type === 'search') {
      ajax.list.splice(0, ajax.list.length, ...list);
    } else if (type === 'scrollDown') {
      ajax.list.push(...list);
    } else if (type === 'update') {
      list.map(r => {
        let index = ajax.list.findIndex(row => r.id === row.id);
        if (index > -1) {
          ajax.list.splice(index, 1, r);
        }
      });
    }
  };
  // 触发子组件更新事件
  const sonChange = ({ type, val }) => {
    if (type == 'scrollDown') {
      if (total.value === ajax.list.length) {
        toastFn(toastRef.value, '已经到底了，滑不动啦', 'error');
        return;
      }
      params.currentPage++;
    } else if (type === 'search') {
      if (!val.start || !val.start) {
        val.start = '';
        val.end = '';
      }
      params.currentPage = 1;
      Object.keys(val).map(key => {
        params[key] = val[key];
      });
    }
    httpHomeRecommend(type);
  };
  defineExpose({ sonComputerEventFn, sonChange });
  let onCollectSuccess = (val1, val2) => {
    let index = ajax.list.findIndex(r => r.id === val1);
    ajax.list[index].collected.id = val2;
  };
  let initShow = ref(false);
  watch(
    () => props.modelValue,
    val => {
      if (!val) return;
      if (val === 1 && !initShow.value) {
        httpHomeRecommend('search');
        initShow.value = true;
      }
    },
    { immediate: true }
  );
</script>

<style lang="scss" scoped>
  .course {
    display: flex;
    // height: 100%;
    overflow: hidden;
    flex-wrap: wrap;
    margin-bottom: 105rpx;
    width: 100%;
    &-empty {
      color: #808080;
      font-size: 26rpx;
      margin: 0 26rpx;
      width: 100%;
      &-text {
        text-align: center;
        margin-top: 21rpx;
        border-bottom: 1px solid #545454;
        padding-bottom: 49rpx;
      }
    }
    .item {
      width: 49%;
      border-radius: 4px;
      position: relative;
      margin-top: 16rpx;
      padding-left: 17rpx;
      box-sizing: border-box;
    }
  }
</style>
